package cc.booku.owlbox.AppUpdate;


import android.app.Activity;

import android.content.Context;


import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;

import java.io.File;
import java.io.IOException;

import cc.booku.owlbox.FileOperations.FileoOperations;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;

import static cc.booku.owlbox.FileOperations.FileoOperations.fileIsExists;

/**
 * Created by yangwenlong on 2020/5/22.
 */


public class AppUpdate {

    String downLoadurl = Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator + "AppVersion" + File.separator;

    //获取版本地址
    //解析json
    //充填到窗口
    //下载更新，调用广播

    //本类主要目的处理链接，获取版本号，返回是否需要更新
    private void AppVersion(String url) {

//请求数据库数据
        OkHttpClient client = new OkHttpClient();
        Request request = new Request
                .Builder()
                .url(url)//要访问的链接
                .build();

        Call call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String res = response.body().string();
                //Log.i("response===========>",res);

                // Mtoast30(res);
                pcdata(res);

            }
        });

    }


    //解析字符串
    private void pcdata(String json) {


        //返回版本信息，版本更新内容，下载地址，时间
        //使用json解析字符串，略
        //取其中最新的日期
        //发送最新的一条更新版本，推荐直接由服务器处理

        String version, title, time, content, down_url;

        //判断是否和以前的版本相同，如果相同，不处理


    }

    private void deleteRevisions(final Activity activity) {

        //如果存在以前版本，就删除
        //获取版本号
        String versioncode = packageName(activity);

        if (fileIsExists(downLoadurl + "app-release.apk")) {
            FileoOperations.deleteFile(activity, downLoadurl + "app-release.apk");
        }
    }


    //获取包名
    public static String packageName(Context context) {
        PackageManager manager = context.getPackageManager();
        String name = null;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            name = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return name;
    }


}
